﻿#include "FITKNastranBDFWriter.h"

#include "FITKNastranAdaptorCase.h"
#include "FITKNastranBDFIOInterface.h"
#include "InpNastranWriterHelper.h"

namespace Nastran
{
    FITKNastranBDFWriter::FITKNastranBDFWriter(FITKNastranBDFIOInterface * compInterface, bool & success)
        :_isSuccess(success), _compInterface(compInterface)
    {
        if (nullptr == _compInterface)
            return;
        _caseData = _compInterface->getDataObjectT<AbaqusData::FITKDataCase>("Model");
    }

    void FITKNastranBDFWriter::run()
    {
        _isSuccess = false;
        if (nullptr == _caseData || !(this->openFileStream()))
        {
            return;
        }
        InpNastranWriterHelper helper(_caseData);
        helper.setWriter(this);
        //以下为实际写入逻辑
        QTextStream* stream = this->getStream();
        *stream << "$$ 627920737A77" << "\r\n";

        AbaqusData::FITKDataCase tempCaseData;
        // Create an adaptor for Nastran using the factory with the temporary case data
        auto adaptor = FITKIOADAPTORFACTORY->createT<Nastran::FITKNastranAdaptorCase>("BDF", &tempCaseData);
        // Check if the adaptor is null, if so, log an error message
        if (nullptr == adaptor)
        {
            consoleMessage(3, "null ptr error for FITKNastranAdaptorCase");
        }
        else
        {
            // If the adaptor is not null, set the helper, reader, and case data
            adaptor->setWriterHelper(&helper);
            adaptor->setWriter(this);
            adaptor->setCaseData(_caseData);
            // Attempt to adapt the data, if it fails, log an error message
            _isSuccess = adaptor->adaptW();
            if (!_isSuccess)
            {
                consoleMessage(3, "error adapting for case");
            }
        }
        // Delete the adaptor to free memory
        delete adaptor;

        // 关闭文件流
        this->closeFileStream();

    }

    void FITKNastranBDFWriter::consoleMessage(int level, const QString &str)
    {
        switch (level)
        {
        case 1:
            AppFrame::FITKMessageNormal(str);
            break;
        case 2:
            AppFrame::FITKMessageWarning(str);
            break;
        case 3:
            AppFrame::FITKMessageError(str);
            break;
        default:
            AppFrame::FITKMessageError(str);
            break;
        }
    }
}

